<template>
    <div class="table-page">
        <div class="table-search-box" @keyup.enter="search()">
            <div class="search-item">
                <label>统计类型：</label>
                <div class="table-query-input">
                    <el-radio-group
                        v-model="selectData.type"
                        size="medium"
                        @change="clickSearch()"
                    >
                        <el-radio-button label="all">所有</el-radio-button>
                        <el-radio-button label="owner">自营</el-radio-button>
                        <el-radio-button label="group">机构</el-radio-button>
                    </el-radio-group>
                </div>
            </div>
            <!--            <div class="search-item">-->
            <!--                <label>数据展示：</label>-->
            <!--                <div class="table-query-input">-->
            <!--                    <el-radio-group v-model="selectData.dataType" size="medium">-->
            <!--                        <el-radio-button label="all">所有</el-radio-button>-->
            <!--                        <el-radio-button label="noReal"-->
            <!--                            >注水数据</el-radio-button-->
            <!--                        >-->
            <!--                        <el-radio-button label="real">真实数据</el-radio-button>-->
            <!--                    </el-radio-group>-->
            <!--                </div>-->
            <!--            </div>-->
        </div>
        <div
            v-if="selectData.type !== 'owner'"
            class="table-search-box"
            @keyup.enter="search()"
        >
            <div class="search-item">
                <label>机构名称：</label>
                <div class="table-query-input">
                    <el-select
                        v-model="queryData.id"
                        filterable
                        clearable
                        placeholder="请选择机构"
                        remote
                        reserve-keyword
                        :remote-method="loadXx"
                    >
                        <el-option
                            v-for="item in departments"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        >
                        </el-option>
                    </el-select>
                </div>
            </div>
            <div class="search-item">
                <label>所属大区：</label>
                <div class="table-query-input">
                    <el-select
                        v-model="queryData.areaCode"
                        filterable
                        clearable
                        placeholder="请选择大区"
                    >
                        <el-option
                            v-for="item in areas"
                            :key="item.code"
                            :label="item.name"
                            :value="item.code"
                        >
                        </el-option>
                    </el-select>
                </div>
            </div>
            <div class="search-item">
                <label>所属区域：</label>
                <div class="table-query-input">
                    <el-select
                        v-model="queryData.regionCode"
                        filterable
                        clearable
                        placeholder="请选择区域"
                    >
                        <el-option
                            v-for="item in regions"
                            :key="item.code"
                            :label="item.name"
                            :value="item.code"
                        >
                        </el-option>
                    </el-select>
                </div>
            </div>
        </div>
        <div class="table-search-box" @keyup.enter="search()">
            <div class="search-item" style="display: block;">
                <label>时间段：</label>
                <el-date-picker
                    v-model="queryData.times"
                    type="daterange"
                    align="right"
                    unlink-panels
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    :picker-options="pickerOptions"
                >
                </el-date-picker>
            </div>
        </div>
        <div class="table-search-box" @keyup.enter="search()">
            <div class="search-item" style="display: block;">
                <label>统计来源：</label>
                <el-checkbox
                    v-model="sourceTypeAll"
                    :indeterminate="sourceTypeIndeterminate"
                    @change="handleCheckAllChange"
                >全选
                </el-checkbox
                >
                <span style="margin: 0 15px;"></span>
                <el-checkbox-group
                    v-model="queryData.sourceTypes"
                    style="display: inline;"
                    @change="handleCheckedSourceTypeChange"
                >
                    <el-checkbox
                        v-for="type in sourceTypes"
                        :key="type.value"
                        :label="type.value"
                    >{{ type.label }}
                    </el-checkbox>
                </el-checkbox-group>
            </div>
        </div>
        <div class="table-search-box" @keyup.enter="search()">
            <div class="search-item">
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    :loading="tableLoading"
                    @click="clickSearch()"
                >搜索
                </el-button>
            </div>
            <div class="search-item">
                <el-button
                    icon="el-icon-refresh"
                    :loading="tableLoading"
                    @click="resetSearch()"
                >重置
                </el-button>
            </div>
            <div class="search-item">
                <el-button
                    type="primary"
                    icon="el-icon-download"
                    :loading="tableLoading"
                    @click="exportExcel('#tabId', '总览')"
                >导出
                </el-button>
            </div>
            <div class="search-item">
                <el-button
                    type="primary"
                    icon="el-icon-finished"
                    :loading="tableLoading"
                    :disabled="compareDisable"
                    @click="toDetail(tableSelect)"
                >详情
                </el-button>
            </div>
        </div>
        <div class="table-data-box">
            <el-table
                id="tabId"
                ref="table"
                v-loading="tableLoading"
                :data="tableData"
                border
                style="width: 100%;min-height:40em"
                row-key="id"
                @selection-change="tableSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center">
                </el-table-column>
                <el-table-column
                    prop="name"
                    label="机构名称"
                    min-width="200"
                ></el-table-column>
                <el-table-column
                    prop="areaName"
                    label="所属大区"
                ></el-table-column>
                <el-table-column prop="regionName" label="所在地区">
                </el-table-column>
                <el-table-column prop="extra.accessLog" label="访问量">
                    <template v-slot:default="scope">
                        <p
                            v-html="dataShow(scope.row, 'accessLog')"
                        ></p></template
                    >
                </el-table-column>
                <el-table-column prop="extra.useLog" label="使用人次"
                >
                    <template v-slot:default="scope">
                        <p v-html="dataShow(scope.row, 'useLog')"></p></template
                    >
                </el-table-column>
                <el-table-column prop="extra.paperUseLog" label="试卷使用量"
                >
                    <template v-slot:default="scope">
                        <p
                            v-html="dataShow(scope.row, 'paperUseLog')"
                        ></p></template
                    >
                </el-table-column>
                <el-table-column prop="extra.questionUseLog" label="试题使用量"
                >
                    <template v-slot:default="scope"
                    ><p
                        v-html="dataShow(scope.row, 'questionUseLog')"
                    ></p></template
                    >
                </el-table-column>
                <el-table-column prop="extra.registerLog" label="注册人数"
                >
                    <template v-slot:default="scope"
                    ><p
                        v-html="dataShow(scope.row, 'registerLog')"
                    ></p></template
                    >
                </el-table-column>
                <el-table-column prop="extra.timeUseLog" label="使用时长(分钟)"
                >
                    <template v-slot:default="scope"
                    ><p
                        v-html="dataShow(scope.row, 'timeUseLog')"
                    ></p></template
                    >
                </el-table-column>
                <el-table-column
                    prop="extra.timeUseLogAvg"
                    label="平均使用时长(分钟)"
                >
                    <template v-slot:default="scope"
                    ><p
                        v-html="dataShow(scope.row, 'timeUseLogAvg')"
                    ></p></template
                    >
                </el-table-column>
                <el-table-column prop="extra.downloadLog" label="下载次数"
                >
                    <template v-slot:default="scope"
                    ><p
                        v-html="dataShow(scope.row, 'downloadLog')"
                    ></p></template
                    >
                </el-table-column>
                <el-table-column
                    label="操作"
                    align="center"
                    width="100"
                >
                    <template slot-scope="scope">
                        <el-button
                            v-if="!scope.row.edit && scope.row.id > -2"
                            lass="primary"
                            type="text"
                            size="mini"
                            icon="el-icon-edit"
                            :loading="scope.row.opLoading"
                            @click="toDetail([scope.row.id])"
                        >详情
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div v-if="pageData.total" class="xy-between table-page-box">
            <el-pagination
                background
                :current-page.sync="pageData.currentPage"
                :page-sizes="pageData.pageSizes"
                :page-size.sync="pageData.pageSize"
                layout="total,  prev, pager, next, sizes, jumper"
                :total="pageData.total"
            >
            </el-pagination>
        </div>
    </div>
</template>

<script>
import {TablePage} from "@/layout/mixin/iVue.js";
import {mapState} from "vuex";
import {get} from "@/api/request";
import groupUseLogComponent from "@/views/models/vrs/group/groupLogDetail";
import FileSave from "file-saver";
import XLSX from "xlsx";
import {
    tableRow2ChildrenList,
    logFiledSet,
    sourceType,
    listAddAll
} from "./groupLog.js";

export default {
    name: "GroupLog",
    components: {groupUseLogComponent},
    mixins: [TablePage],
    data() {
        return {
            departments: null,
            queryData: {
                id: null,
                areaCode: null,
                base: true,
                sourceTypes: [
                    "PcZhiYe",
                    "PcGjtk",
                    "AppZhiYe",
                    "AppGjtk",
                    "WpZSZhiYe",
                    "WpZSGjtk"
                ],
                regionCode: null,
                times: null
            },
            selectData: {
                type: "all",
                dataType: "all"
            },
            format: {
                dateTimeFormat: "yyyy-MM-dd HH:mm:ss",
                dateFormat: "yyyy-MM-dd",
                monthFormat: "yyyy-MM",
                yearFormat: "yyyy"
            },
            sourceTypes: sourceType,
            areas: null,
            regions: null,
            sourceTypeAll: true,
            sourceTypeIndeterminate: false,
            flag: {
                dataFlag: false,
                areaFlag: false,
                regionFlag: false
            }
        };
    },
    computed: {
        pickerOptions() {
            return {
                shortcuts: [
                    {
                        text: "最近一周",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 7
                            );
                            picker.$emit("pick", [start, end]);
                        }
                    },
                    {
                        text: "最近一个月",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 30
                            );
                            picker.$emit("pick", [start, end]);
                        }
                    },
                    {
                        text: "最近三个月",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 90
                            );
                            picker.$emit("pick", [start, end]);
                        }
                    }
                ]
            };
        },
        compareDisable() {
            return (
                !this.tableSelect ||
                this.tableSelect.filter(v => v > -2).length === 0
            );
        }
    },
    watch: {},
    created() {
        this.loadArea();
        this.loadRegion();
        this.loadXx();
    },
    mounted() {
    },
    methods: {
        loadXx(query) {
            return get("/user/sys/group/list", {
                name: query,
                size: 1000
            }).then(res => {
                this.departments = res
            });
        },
        exportExcel(dom, title) {
            let workBook = XLSX.utils.table_to_book(
                document.querySelector(dom)
            );
            console.log(workBook)
            let write = XLSX.write(workBook, {
                bookType: "xlsx",
                bookSST: true,
                type: "array",
                sheet: "sheet1",
                Props: ["name"]
            });
            try {
                FileSave.saveAs(
                    new Blob([write], {
                        type: "application/octet-stream"
                    }),
                    title + ".xlsx"
                );
            } catch (e) {
                console.log(e);
            }
        },
        search(queryData) {
            const w = () => {
                this.tableLoading = true;
                if (this.queryData.id || this.queryData.areaCode || this.queryData.regionCode || this.queryData.times) {

                } else {
                    this.tableData.unshift({
                        id: "0",
                        name: "默认机构",
                        children: null
                    });
                    this.tableData.unshift({
                        id: -1,
                        name: "全部机构",
                        children: null
                    });
                }
            };
            const w1 = () => {
                return Promise.all(
                    this.tableData.map(row => {
                        var s = this.queryData.times && this.queryData.times[0];
                        var e = this.queryData.times && this.queryData.times[1];
                        return get("/log-records/admin-record-list", {
                            groupId: row.id,
                            sourceTypes: this.queryData.sourceTypes,
                            start: s ? s : undefined,
                            end: e ? e : undefined
                        })
                            .then(v => {
                                return listAddAll(v);
                            })
                            .then(result => {
                                logFiledSet(this, row, result);
                                row.children = tableRow2ChildrenList(
                                    row,
                                    result,
                                    this.queryData.sourceTypes
                                );
                            });
                    })
                );
            };
            if (this.selectData.type === "owner") {
                this.tableLoading = true;
                this.tableData = [];
                w();
                w1().finally(() => {
                    this.tableLoading = false;
                });
                return;
            }
            this.loadTable("user/sys/group/page", {}, true, row => {
                row.children = [];
                return row;
            })
                .then(() => {
                    if (
                        this.selectData.type === "all" &&
                        this.pageData.currentPage === 1
                    ) {
                        w();
                    }
                    this.tableLoading = true;
                    return w1();
                })
                .finally(() => {
                    this.tableLoading = false;
                });
        },
        groupLog(data, title) {
        },
        initTime() {
            if (!this.queryData.time || this.queryData.time.length === 0) {
                const end = new Date();
                const start = new Date();
                start.setDate(1);
                // start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                this.queryData.time = [start, end];
            }
        },
        dataShow(row, k) {
            if (row[k]) {
                let c = row[k].allCount.toFixed(0);
                let rc = row[k].realAllCount.toFixed(0);
                if (this.queryData.times) {
                    if(k==="timeUseLogAvg"){
                        rc = row[k].realTodayCount.toFixed(2);
                    }else {
                        c = row[k].todayCount.toFixed(0);
                        rc = row[k].realTodayCount.toFixed(0);
                    }
                }
                return rc;
                if (this.selectData.dataType === "real") return rc;
                if (this.selectData.dataType === "noReal") return c - rc;
                return `${c} / <span  ${
                    rc !== c ? 'class="red"' : ""
                }>${rc} </span>`;
            }
            return "0/0";
        },
        handleCheckAllChange(val) {
            this.queryData.sourceTypes = val
                ? this.sourceTypes.map(v => v.value)
                : [];
            this.sourceTypeIndeterminate = false;
        },
        handleCheckedSourceTypeChange(value) {
            let checkedCount = value.length;
            this.sourceTypeAll = checkedCount === this.sourceTypes.length;
            this.sourceTypeIndeterminate =
                checkedCount > 0 && checkedCount < this.sourceTypes.length;
        },
        loadArea(query) {
            return this.flagPromise(
                get("/user/sys/dict/detail/listByTypeCode", {
                    name: query,
                    typeCode: "area"
                }).then(res => {
                    this.areas = res;
                    return res;
                }),
                "areaFlag"
            );
        },
        loadRegion() {
            this.regions = [];
            this.queryData.regionCode = null;
            return this.flagPromise(
                get("/user/sys/dict/detail/listByTypeCode", {
                    typeCode: "region"
                }).then(res => {
                    this.regions = res;
                    return res;
                }),
                "regionFlag"
            );
        },
        toDetail(ids) {
            var s = this.queryData.times && this.queryData.times[0];
            var e = this.queryData.times && this.queryData.times[1];
            this.$router.push({
                path: "./log-detail",
                query: {
                    groupId: ids.filter(v => v > -2).join(","),
                    start: s ? s : undefined,
                    end: e ? e : undefined
                }
            });
        }
    }
};
</script>

<style lang="scss" scoped>
.table-search-box {
    margin-bottom: 0.2em;
}

.table-data-box {
    ::v-deep {
        .red {
            color: red;
        }
    }
}
</style>
